from sqlalchemy import Select, delete
from sqlmodel import SQLModel, Field, select, Session

from settings import auto_session
import user
import permission


class UserPermission(SQLModel, table=True):
    __tablename__ = "user_permission"
    user_id :int = Field(foreign_key = "userinfo.id", ondelete = "CASCADE", primary_key=True)
    permission_id :int = Field(foreign_key = "permission.id", ondelete = "CASCADE", primary_key=True)

@auto_session
def search_user_permission(user_id :int ,permission_id :int ,session :Session = None ) -> bool|None:
    """
    根据用户id和权限id搜索用户权限
    搜索到则输出True，否则输出False，错误则输出None
    """
    statement :Select = (select(UserPermission).
                        where(UserPermission.user_id == user_id,
                              UserPermission.permission_id == permission_id))
    result = session.exec(statement).first()
    if result:
        return True
    else:
        return False

@auto_session
def search_user_all_permissions(user_id: int ,session :Session = None ) -> list[int]:
    """
    根据用户id搜索用户的所有权限
    返回这个用户的所有权限id
    """
    statement :Select = (select(UserPermission.permission_id).
                        where(UserPermission.user_id == user_id))
    result :list[int] = session.exec(statement).all()
    return result

@auto_session
def insert_user_permissions(user_id: int, permission_ids: list[int], session: Session = None) -> int|None:
    """
    批量插入用户权限
    插入成功则输出插入数量，已存在的权限不在插入数中，插入失败输出-1，错误则输出None
    """
    if not permission_ids:
        return 0

    # 查询已存在的权限关联
    existing_stmt = select(UserPermission.permission_id).where(
        UserPermission.user_id == user_id,
        UserPermission.permission_id.in_(permission_ids)
    )
    existing_ids = set(session.exec(existing_stmt).all())

    try:
        # 批量创建新关联
        new_permissions = [
            UserPermission(user_id=user_id, permission_id=pid)
            for pid in permission_ids
            if pid not in existing_ids
        ]

        if new_permissions:
            session.bulk_save_objects(new_permissions)
            session.flush()

        return len(new_permissions)
    except Exception as e:
        print(e)
        session.rollback()
        return -1

@auto_session
def delete_user_permissions(user_id: int, permission_ids: list[int], session: Session = None) -> int | None:
    """
    批量删除用户权限
    删除成功则输出删除数量，权限不存在的不计数，删除失败输出-1，错误则输出None
    """
    if not permission_ids:
        return 0

    try:
        # 批量删除关联记录
        delete_stmt = delete(UserPermission).where(
            UserPermission.user_id == user_id,
            UserPermission.permission_id.in_(permission_ids)
        )
        result = session.exec(delete_stmt)
        session.flush()

        return result.rowcount

    except Exception as e:
        print(e)
        session.rollback()
        return -1

@auto_session
def delete_all_user_permissions(user_id: int, session: Session = None) -> int | None:
    """
    删除用户所有权限
    删除成功则输出删除数量，权限不存在的不计数，删除失败输出-1，错误则输出None
    """
    try:
        # 删除关联记录
        delete_stmt = delete(UserPermission).where(
            UserPermission.user_id == user_id
        )
        result = session.exec(delete_stmt)
        session.flush()

        return result.rowcount
    except Exception as e:
        print(e)
        session.rollback()
        return -1

@auto_session
def reset_user_permissions(user_id: int, session: Session = None) -> int | None:
    """
    重置用户权限
    重置成功则输出新的权限数量，重置失败输出-1，错误则输出None
    """
    level = user.get_user_privilege(id = user_id, session = session)
    if level is None:
        return None
    delete_all_user_permissions(user_id=user_id, session = session)
    permissions = permission.get_all_privilege_not_greater_than_level(level=level, session=session)
    permission_ids = [p['id'] for p in permissions]
    return insert_user_permissions(user_id=user_id, permission_ids=permission_ids, session=session)